package org.learn.mq.rabbit.workqueue;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 接收rabbitmq的消息
 *
 * @author xianglujun
 * @date 2019/7/8 15:28
 */
@Slf4j
public class DurableWorker {

    private static final String QUEUE_NAME = "hello";

    public static void main(String[] args) {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.172.128");

        try {
            Connection connection = connectionFactory.newConnection();
            Channel channel = connection.createChannel();

            // 告知RabbitMQ在重启或者宕机的情况下, 不要丢弃queue
            // 如果创建的queue已经存在, 将可能抛出异常.
            boolean durable = true;
            channel.queueDeclare(QUEUE_NAME, durable, false, false, null);

            // accept only one unack-ed message at a time (see below)
            channel.basicQos(1);

            // 输出信息
            System.out.println("[*] waiting for messages, To exit process CTRL+C");

            // 定义回调类, 消息是通过server端执行push操作, 将消息推送到客户端,
            // 客户端通过在接收到消息回调的方式, 对消息进行处理
            DeliverCallback deliverCallback = (consumerTag, message) -> {
                String recvMsg = new String(message.getBody(), "utf-8");
                System.out.println("[x] received '" + recvMsg + "'");

                try {
                    doWork(recvMsg);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                } finally {
                    System.out.println("[x] done");
                }
            };

            // acknowledgment is covered below
            // 通过将该值设置为false, 用ack控制客户端是否接收到消息
            boolean autoAck = false;
            channel.basicConsume(QUEUE_NAME, autoAck, deliverCallback, consumerTag -> {
            });
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }

    private static void doWork(String task) throws InterruptedException {
        for (char ch : task.toCharArray()) {
            if (ch == '.') {
                Thread.sleep(1000);
            }
        }
    }
}
